﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Windows;
using GamePlugin.Logics.Core;
using System.Xml;

namespace GamePlugin.Logics.Data
{
    public class LengendItemList : DependencyObject
    {
        public LengendItemList()
        {
            Children = new ObservableCollection<string>();
        }

        public void Sort()
        {
            List<string> names = Children.ToList<string>();
            names.Sort();
            Children.Clear();
            for (int i = 0; i < names.Count; i++)
                Children.Add(names[i]);
        }

        public bool Contain(string name)
        {
            string temp = Helper.GetLengendItemName(name);
            if (temp.Length > 0)
            {
                name = temp;
                name = name.Substring(1, name.Length - 2);
            }
            else
            {
                //name = name;
            }
            return Children.ToList<string>().IndexOf(name) >= 0;
        }

        public static readonly DependencyProperty ChildrenProperty =
            DependencyProperty.Register("Children", typeof(ObservableCollection<string>), typeof(LengendItemList), null);
        public ObservableCollection<string> Children
        {
            get { return (ObservableCollection<string>)GetValue(ChildrenProperty); }
            set { SetValue(ChildrenProperty, value); }
        }

        public void ReadXml(XmlNode root)
        {
            Children.Clear();

            root = root.SelectSingleNode("./" + "Root");

            var countNode = root.SelectSingleNode("./" + "Count");
            int count = int.Parse(countNode.InnerText);

            for (int i = 0; i < count; i++)
            {
                var node = root.SelectSingleNode("./" + "Name" + i.ToString());
                Children.Add(node.InnerText);
            }

        }

        public void WriteXml(XmlWriter writer)
        {
            Sort();

            writer.WriteStartElement("Root");

            writer.WriteStartElement("Count");
            writer.WriteString(Children.Count.ToString());
            writer.WriteFullEndElement();

            for (int i = 0; i < Children.Count; i++)
            {
                writer.WriteStartElement("Name" + i.ToString());
                writer.WriteString(Children[i]);
                writer.WriteFullEndElement();
            }

            writer.WriteFullEndElement();
        }
    }
}
